import cls from './index.module.less';
import { useEffect, useState, VFC } from 'react';
import { CommonList } from '@common';
import { Form, Button, Input, Modal } from 'antd';
import { Rule } from 'antd/lib/form'
import { EditOutlined, DeleteOutlined, PlusOutlined, MinusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { v4 } from 'uuid';
import { len } from '@common';
import { setegid } from 'process';
const modalFormRule: {[key: string]:Rule[]} = {
  name: [
    {required: true, message: '名称必填'},
    {
      validator: (_: any, value: null|string, callback) => {
        if(typeof value !== 'string') {
          return callback();
        }
        let length = len(value);
        if(length > 20) {
          return callback('名称不能超过20个字符');
        }
        return callback();
      }
    }
  ],
  key: [
    {required: true, message: 'cookie名称不能为空'}
  ],
  value: [
    {required: true, message: 'cookie的值不能为空'}
  ],
  cookies: [
    {required: true, message: '至少存在一个cookie'},
    {
      validator: (_: any, value: null|{key: string, value: string}[], callback) => {
        if(!Array.isArray(value)) {
          return  callback();
        }
        if(value.length === 0) {
          return callback('至少存在一个cookie');
        }
        return callback();
      }
    }
  ]
}
interface EnvStruct {
  id: string;
  name: string;
  cookies: { key: string, value: string }[]
}
const { useForm, Item } = Form;
const ApiEnvField: VFC<{ value?: EnvStruct[], onChange?: (val: EnvStruct[]) => any }> = (props) => {
  const valueArr: EnvStruct[] = Array.isArray(props.value) ? props.value : [];
  const [visible, setVisible] = useState(false);
  const [form] = useForm();
  const [editId, setEditId] = useState<string|number|null>(null);
  const onModalSure = () => {
    form.validateFields().then(res => { // 表单验证通过
      console.log(res);
      if(!editId) {
        props.onChange && props.onChange([...valueArr, Object.assign({id: v4()}, res)]);
      } else {
        let findIndex = valueArr.findIndex(item => item.id === editId);
        if(findIndex !== -1) {
          valueArr[findIndex] = Object.assign(valueArr[findIndex], res);
          props.onChange && props.onChange([...valueArr]);
        }
        setEditId(null);
      }
      setVisible(false);
    });
  }
  const onEditEnv = (id: string) => {
    let findValue = valueArr.find(item => item.id === id);
    if (!findValue) return;
    setEditId(findValue.id);
    form.setFieldsValue({
      id: findValue.id,
      name: findValue.name,
      cookies: findValue.cookies
    });
    setVisible(true);
  }
  const onDeleteEnv = (id: string) => {
    let idx = valueArr.findIndex(item => item.id === id);
    valueArr.splice(idx, 1);
    props.onChange && props.onChange([...valueArr])
  }
  const onAddEnv = () => {
    form.setFieldsValue({
      id: null,
      name: null,
      cookies: []
    });
    setVisible(true);
  }
  const onModalCancel = () => {
    setVisible(false);
  }
  // return (<></>)
  // @ts-ignore
  return (
    <div className={cls.envFiled}>
      {valueArr.map((item) => (
        <div key={item.id} className={cls.envItem}>
          <div className={cls.evnName}>{item.name}</div>
          <div className={cls.envOpereate}>
            <div className={cls.btn} onClick={() => onEditEnv(item.id)}>
              <EditOutlined />
            </div>
            <div className={cls.btn} onClick={() => onDeleteEnv(item.id)}>
              <DeleteOutlined />
            </div>
          </div>
        </div>
      ))}
      <div className={cls.envItemAdd}>
        <Button type="primary" style={{ width: '100%' }} onClick={() => onAddEnv()}><PlusOutlined /></Button>
      </div>
      <Modal title="添加环境" transitionName="" maskTransitionName="" visible={visible} zIndex={1001} onCancel={onModalCancel} onOk={onModalSure}>
        <Form form={form}>
          <Item label="环境名称" name="name" rules={modalFormRule.name}>
            <Input />
          </Item>
          <div className={cls.cookieField}>
            <div className={cls.label}>cookie：</div>
            <div className={cls.fieldList}>
              {/* @ts-ignore */}
              <Form.List name="cookies" rules={modalFormRule.cookies} >
                {((fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => {
                      return (
                        <div key={key} className={cls.fieldListItem}>
                          <Item {...restField} style={{ marginBottom: '0px', flex: '0.5' }} name={[name, 'key']} rules={modalFormRule.key} >
                            <Input />
                          </Item>
                          <MinusOutlined className={cls.spliteLine}/>
                          <Item {...restField} style={{ marginBottom: '0px', flex: 0.5 }} name={[name, 'value']} rules={modalFormRule.value}>
                            <Input />
                          </Item>
                          <div className={cls.removeItem} onClick={() => remove(name)} style={{ padding: '0px 10px', cursor: 'pointer' }}>
                            <MinusCircleOutlined style={{ fontSize: '16px' }} />
                          </div>
                        </div>
                      )
                    })}
                    <Button type="primary" key="add" className={cls.addBtn} onClick={() => add({ key: null, value: null })}>添加</Button>
                  </>
                ))}
              </Form.List>
            </div>
          </div>

        </Form>
      </Modal>
    </div>

  );
}
export const Create: VFC<{}> = (props) => {
  const [form] = useForm<any>();
  useEffect(() => {
    form.setFieldsValue({
      envs: []
    });
  }, [form]);
  const onSure = () => {

  }
  const onCancel = () => {

  }
  return (
    <CommonList.HeaderBtn initVisible={false} btn={<Button type="primary">新建</Button>} onSure={onSure} title='新建项目'>
      <div className={cls.createProjectContainer}>
        <Form form={form}>
          <Item label="项目封面" name="cover">
            <Input />
          </Item>
          <Item label="项目名称" name="name">
            <Input />
          </Item>
          <Item label="接口前缀" name="apiPrefix">
            <Input />
          </Item>
          <Item label="接口环境" name="envs">
            <ApiEnvField />
          </Item>
          <Item label="描述">
            <Input.TextArea rows={5} placeholder="项目描述" />
          </Item>
        </Form>
      </div>
    </CommonList.HeaderBtn>
  );
}